package cn.wolfcode.web.interceptor;

import cn.wolfcode.anno.RequirePermission;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.exception.PermissionException;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.UserContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class PermissionInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Employee employee = UserContextUtil.getEmployee();
        
        // 判断是否是管理员
        if (employee.isAdmin()){
            return true;
        }
        
        // 判断处理方法是否贴自定义注解
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        RequirePermission annotation = handlerMethod.getMethodAnnotation(RequirePermission.class);
        // 处理方法没贴自定义注解
        if (annotation == null){
            return true;
        }
        // 不是管理员 贴了自定义注解
        // 查询用户的权限
        List<String> expressions = UserContextUtil.getExpressions();
        // 用户访问的页面在自身的权限内
        if (expressions.contains(annotation.expression())){
            return true;
        }

        // request.getRequestDispatcher("/permission/noPermission").forward(request,response);
        // return false;
        throw new PermissionException("你没有权限");
    }
}
